﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UniRlv.Utility;

namespace UniRlv.UI.Main
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            //非UI异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //处理未捕获的异常   
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常   
            Application.ThreadException += Application_ThreadException;
            
            //处理线程异常
            TaskScheduler.UnobservedTaskException += (sender, e) =>
            {
                string log = GetExceptionMsg(e.Exception, "未捕获线程异常: " + (e.Exception).ToString());
                AppendExceptionLog(log);
            };

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            int processCount = 0;

            Process[] pa = Process.GetProcesses();//获取当前进程数组。  
            Console.WriteLine("当前进程："+Process.GetCurrentProcess().ProcessName);
            foreach (Process PTest in pa)
            {
                if (PTest.ProcessName == Process.GetCurrentProcess().ProcessName)
                {
                    processCount += 1;
                }
            }

            if (processCount > 1)
            {
                DialogResult dr;
                dr = MessageBox.Show(Process.GetCurrentProcess().ProcessName + "程序已经在运行！", "退出程序", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return; //Exit;  
            }


            string dll32 = System.Windows.Forms.Application.StartupPath + "\\Seagull.BarTender.Print_X86.DLL";
            string dll64 = System.Windows.Forms.Application.StartupPath + "\\Seagull.BarTender.Print_X64.DLL";
            string dllpath = System.Windows.Forms.Application.StartupPath + "\\Seagull.BarTender.Print.dll";

            if (IntPtr.Size == 4)
            {
                //做32位的东西。
                try
                {
                    using (FileStream fs = File.Create(dllpath))
                    {
                    }
                    File.Copy(dll32, dllpath, true);
                }

                catch
                {
                    Console.WriteLine("ERR");
                }

            }
            else
            {
                //做64位的事情
                try
                {
                    using (FileStream fs = File.Create(dllpath)) { }
                    File.Copy(dll64, dllpath, true);
                }
                catch
                {
                    Console.WriteLine("ERR");
                }
            }


            string dir = Path.Combine(Application.StartupPath, "exception");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            FrmLogin frm = new FrmLogin();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                Application.Run(FrmMain.GetInstance());
            }
            else
            {
                if (WorkSpace.GetInstance().IfHasInit)
                {
                    WorkSpace.GetInstance().Quit();
                }
            }
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            string log = GetExceptionMsg(e.Exception, "未捕获的UI线程异常: " + (e.Exception).ToString());
            AppendExceptionLog(log);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string log = GetExceptionMsg(e.ExceptionObject as Exception, "未捕获的其他异常: " + (e.ExceptionObject as Exception).ToString());
            AppendExceptionLog(log);
        }

        static public void AppendExceptionLog(string s)
        {
            try
            {
                string log = string.Format("[{0}] {1}\r\n", DateTime.Now.ToString("HH:mm:ss"), s);
                Console.WriteLine(log);

                string path = Path.Combine(Application.StartupPath, "exception");
                path = string.Format("{0}\\{1}_exception.txt", path, DateTime.Now.ToString("yyyyMMdd"));
                File.AppendAllText(path, log);
            }
            catch (Exception)
            {

            }
        }


        /// <summary>
        /// 生成自定义异常消息
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="backStr">备用异常消息：当ex为null时有效</param>
        /// <returns>异常字符串文本</returns>
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
                sb.AppendLine("【异常方法】：" + ex.TargetSite);
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");

            return sb.ToString();
        }
    }
}
